from flask.json import jsonify

from info.models import User, Category, News
from info.utils.response_code import RET
from . import index_blu
from flask import render_template, current_app, session, request


@index_blu.route('/')
def index():
    """
    是否登录  取user_id
    如取不到 ： 则显示原有界面
    如 取到 ：　显示用户头像　昵称
    :return:
    """
    # 获取到当前登录用户的id
    user_id = session.get("user_id")
    # 通过id获取用户信息
    user = None
    if user_id:
        try:
            user = User.query.get(user_id)
        except Exception as e:
            current_app.logger.error(e)

    """新闻排行列表的显示"""
    news_list = []
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(6)
    except Exception as e:
        current_app.logger.error(e)
    news_dict_list = []
    for news in news_list:
        news_dict_list.append(news.to_basic_dict())

    """首页顶部新闻分类"""
    category_list = []
    try:
        category_list = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
    category_dict_list = []
    for category in category_list:
        category_dict_list.append(category.to_dict())

    data = {
        "user": user.to_dict() if user else None,
        "news_dict_list": news_dict_list,
        "category_dict_list": category_dict_list
    }
    return render_template("news/index.html", data=data)


@index_blu.route("/newslist")
def get_news_list():
    """获取新闻首页数据"""
    # 1. 获取参数
    cid = request.args.get("cid", "1")
    page = request.args.get("page", "1")
    per_page = request.args.get("per_page", "10")

    # 2. 校验参数
    try:
        cid = int(cid)
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数不正确")
    # 如果cid不等于1，说明是查找指定分类
    filters = []
    if cid != 1:
        filters.append(News.category_id == cid)
    # 查询数据库，按照指定filters
    try:

        paginate = News.query.filter(*filters).order_by(News.create_time.desc()) \
            .paginate(page, per_page, False)  # type:Pagination
        news_list = paginate.items
        total_page = paginate.pages
        current_page = paginate.page
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询失败")

    # 构造新闻列表的字典数据
    news_dict_list = []
    for news in news_list:
        news_dict_list.append(news.to_dict())
    # 返回数据
    return jsonify(errno=RET.OK, errmsg="OK", totalPage=total_page,
                   currentPage=current_page, newsList=news_dict_list,
                   cid=cid)


@index_blu.route('/favicon.ico')
def favicon():
    return current_app.send_static_file('news/favicon.ico')
